import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ICurrentUserType } from 'src/decorators/current_user';
import { PostEntity } from 'src/entity/posts.entity';
import { PostCreateDto } from 'src/modules/background/post/dto/post.create.dto';
import { PostReqDto } from 'src/modules/background/post/dto/post.req.dto';
import { PostListDetailVo, PostListVo, PostResVo } from 'src/modules/background/post/vo/post.vo';
import { getConnection, Repository } from 'typeorm';

@Injectable()
export class PostService {
    constructor(@InjectRepository(PostEntity) private readonly postEntity: Repository<PostEntity>) { }
    // 文章添加
    async postAdd(userInfo: ICurrentUserType,data: PostCreateDto): Promise<string> {
        try {
            const { id } = userInfo;
            const { title } = data
            if (title) {
                const result: Pick<PostEntity, 'id'> | undefined = await this.postEntity.findOne({ where: { title } })
                if (result) {
                    throw new HttpException(`${title}已存在请勿重复创建`, HttpStatus.OK)
                }
                const postData = JSON.parse(JSON.stringify(data))
                postData.tagIds = postData.tagIds.join(',')
                postData.userId = id
                const post = this.postEntity.create(postData)
                await this.postEntity.save(post)
                return '创建成功'
            }
            throw new HttpException(`文章标题已存在`, HttpStatus.OK)
        } catch (error) {
            throw new HttpException(`创建失败${error}`, HttpStatus.OK)
        }
    }
    // 文章删除
    async destoryPostById(id: number): Promise<string> {
        const result = await this.postEntity.delete(id)
        if (result) {
            return '删除成功'
        } else {
            return '删除失败'
        }
    }
    // 文章查找
    async postListPage(data: PostReqDto): Promise<PostListVo> {
        const { pageNum, pageSize,title ,categoryId,tagIds,id} = data
        const queryConditionList = []
        let tagIdsStr = ''
        if(id){
            queryConditionList.push("post.id = :id");
        }
        if(tagIds){
            tagIdsStr = tagIds.join(',')
        }
        if (title) {
            queryConditionList.push("post.title LIKE :title");
        }
        if (categoryId) {
            queryConditionList.push("post.categoryId = :categoryId");
        }
        if (tagIdsStr) {
            queryConditionList.push("post.tagIds LIKE :tagIds");
        }
        const queryCondition = queryConditionList.join(" AND ")
        const [list, total] = await getConnection()
            .createQueryBuilder(PostEntity, 'post')
            .andWhere(queryCondition, {id, title: `%${title}%`,categoryId,tagIds:`%${tagIdsStr}%`})
            .skip((pageNum - 1) * pageSize)
            .take(pageSize)
            .orderBy({ 'post.createdAt': 'DESC' })
            .printSql()
            .getManyAndCount();
        const result = JSON.parse(JSON.stringify(list))
        result.forEach((el: PostResVo)=>{
            el.tagIds = el.tagIds.split(',').map(Number)
        })
        return {
            posts: result,
            total,
            pageSize,
            pageNum
        }
    }
    // 文章更新
    async modifyPostById(id: number, data: PostCreateDto): Promise<string> {
        const postData = JSON.parse(JSON.stringify(data))
        postData.tagIds = postData.tagIds.join(',')
        const {
            raw: { affectedRows },
        } = await this.postEntity.update(id, postData);
        if (affectedRows) {
            return '修改成功';
        } else {
        return '修改失败';
        }
    }
}
